import { playServices } from '@/api';
import YouXin from 'youxin-js-sdk';
import PVCollector from './PVCollector.js';
import { getMobileUrl } from '@/utils';
export var moreAction = [
  // {
  //   id: '4',
  //   type: 'native',
  //   title: '分享',
  //   icon: `${window.hostOrigin}/static/play/share.png`,
  //   icon_black: `${window.hostOrigin}static/play/share-full.png`,
  //   url: 'vcom://common/share/dialog'
  // }
];

/**
 * 全屏音视频播放 新改动
 * @param {*} backdata
 * @param {*} params
 */
export function playVideoOrAudio (backdata, params, resolve) {
  const datas = backdata;
  let url = '',
    ll = '',
    id = '';
  if (datas.list.length === 1) {
    url = jointPlayDomain(datas.list[0].url, datas.list[0].playUrlFlag);
    id = datas.list[0].id || datas.list[0].fileId || datas.list[0].resId;
  } else if (datas.list.length > 1) {
    let item = datas.list.filter((item) => item.mobileChiefFlag === 1);
    if (item.length === 0) {
      ll = datas.list[0].url;
      url = jointPlayDomain(ll, datas.list[0].playUrlFlag);
      item = datas.list;
    } else {
      ll = item[0].url;
      url = jointPlayDomain(ll, item[0].playUrlFlag);
    }
    id = item[0].id || item[0].fileId || item[0].resId;
  } else {
    YouXin.openWindow({
      url: `${window.hostOrigin}/play/` + JSON.stringify(params), // 网页地址
      title: params.title,
      showHeader: '1'
    });
    return;
  }

  if (url === '') {
    getOtherPlay(params);
    return;
  }

  const moreActions = JSON.parse(JSON.stringify(moreAction)),
    type = getFileType(backdata);
  moreActions.forEach((item) => {
    if (item.id === '4') {
      const shareConfig = {};
      shareConfig.id = id;
      const param = assembleSharePara(shareConfig);
      item.extra = { ...param };
    }
  });
  if (type === 'video') {
    console.log('uuuuu', params);
    const useUrl = window.location.origin;
    YouXin.playVideoWithFullPage({
      url: url,
      data: JSON.stringify(params),
      title: params.title,
      lastPlayTime: params.spendTime,
      uberAction: {
        u: 1, // 增加积分
        s: 5, // 5 代表资源
        r: id // 资源id
      },
      moreAction: moreActions,
      paper: {
        url:
          params.pageItem && params.pageItem !== ''
            ? `${useUrl}/ui/tqms/mobile/v1/s/sync/${params.pageItem.destCode}/start_sync?catId=${params.pageItem
                .sourceCode}&resId=${params.pageItem.destCode}&action=res_common_${params.pageItem.sourceCode}_${params
                .pageItem.destCode}`
            : ''
      }
    });
  } else {
    const audioList = datas.list.filter((item) => {
        return item.url !== '' && item.afterFormat === '2';
      }),
      sources = audioList.map((item) => {
        return {
          title: item.fileName,
          id: item.id || item.fileId || item.resId,
          url: jointPlayDomain(item.url, item.playUrlFlag)
        };
      });
    console.log('sources--', sources, 'id---', id);
    const json = {
      url: url,
      id: id,
      data: JSON.stringify(params),
      title: params.title,
      source: sources,
      lastPlayTime: params.spendTime,
      moreAction: moreActions,
      success: (data) => {
        const items = data.length > 0 && data,
          obj = items.find((item) => item.id === id);
        console.log('音频播放的进度-----', obj);
        if (parseInt(obj.playEnd) === 1) {
          const finish = 100;
          resolve({ finish, obj });
        } else {
          if (parseInt(obj.totalTime) === 0) {
            resolve(0);
          } else {
            if (parseInt(obj.currentTime) < parseInt(obj.totalTime)) {
              const finish = 50;
              resolve({ finish, obj });
            } else if (parseInt(obj.currentTime) >= parseInt(obj.totalTime)) {
              const finish = 100;
              resolve({ finish, obj });
            }
          }
        }
      }
    };
    YouXin.playAudioWithFullPage(json);
  }
}

/**
 * 小窗口播放
 * @param {} item
 * @param {*} params
 */

export function getVideoOrAudioPlay (params, type) {
  // 普通视频播放
  if (window.UxinJsCore) {
    YouXin.openVideoWindow({
      url: `${window.hostOrigin}/play/` + JSON.stringify(params), // 网页地址
      data: JSON.stringify(params),
      title: params.title,
      showHeader: '1' // 是否显示导航：0 隐藏   1 显示（ 默认）
    });
  } else {
    window.open(`${window.location.origin}/play/` + JSON.stringify(params));
  }
}

function getVideoPlayBySP (params, url) {
  // 普通视频播放
  if (window.UxinJsCore) {
    YouXin.openVideoWindow({
      url: url,
      data: JSON.stringify(params),
      title: params.title,
      isShowVideo: params.isShowVideo,
      showHeader: '1'
    });
  } else {
    window.open(url);
  }
}

function getVideoPlay (params, type) {
  // 普通视频播放
  if (window.UxinJsCore) {
    YouXin.openVideoWindow({
      url: `${window.hostOrigin}/play/` + JSON.stringify(params),
      data: JSON.stringify(params),
      title: params.title,
      isShowVideo: params.isShowVideo,
      showHeader: '1'
    });
  } else {
    window.open(`${window.location.origin}/play/` + JSON.stringify(params));
  }
}

/**
 * 非音视频播放
 * @param {*} item
 * @param {*} params
 */

function getOtherPlay (params) {
  // 其他文件播放
  const item = params,
    type = item.destType;
  console.log('parn----', params, `${window.hostOrigin}/play/` + JSON.stringify(params));
  if (parseInt(type) === 2) {
    getPaperPlay(params);
    return;
  }

  if (isApply(params)) {
    getApplyPlay(params);
    return;
  }
  let header = '1',
    screenMode = '0';
  if (params.mu && params.mu !== '') {
    header = isApply(params) ? '0' : '1';
    screenMode = isApply(params) ? '2' : '0';
    params.title = isApply(params) ? '' : params.title;
  }
  YouXin.openWindow({
    url: `${window.hostOrigin}/play/` + JSON.stringify(params), // 网页地址
    title: params.title,
    showHeader: header,
    screenMode: screenMode
  });
}
/**
 *  试卷播放预览
 * @param {*} params
 */

function getPaperPlay (params) {
  const item = params,
    useUrl = window.location.origin;
  YouXin.getWindowId({
    success (WindowId) {
      // 成功方法
      // 打开新窗口
      item.url = `${useUrl}/ui/tqms/mobile/v1/s/sync/${item.id}/start_sync?windowId=${WindowId}&catId=${item.catId}&resId=${item.id}&action=res_${item.catId}_${item.id}&isNeedUploadProgress=1`;
      console.log('url-----', item.url);
      YouXin.openWindow({
        url: item.url,
        title: item.title,
        showHeader: '0'
      });
    }
  });
}

/**
 * 应用播放
 */
function getApplyPlay (params) {
  const item = params,
    useUrl = window.location.origin;
  let header = '1',
    screenMode = '0';
  if (params.mu && params.mu !== '') {
    header = isApply(params) ? '0' : '1';
    if (isSafeArea(params)) {
      screenMode = '0';
    } else {
      screenMode = isLandscape(params) ? '2' : '1';
    }
    params.title = isApply(params) ? '' : params.title;
  }

  if (isNeedNest(params)) {
    YouXin.openWindow({
      url: `${window.hostOrigin}/play/` + JSON.stringify(params), // 网页地址
      title: params.title,
      showHeader: header,
      screenMode: screenMode
    });
  } else {
    // 应用
    if (item.mu !== 'undefined' && item.mu !== '') {
      const regExp = new RegExp('\\>', 'g'),
        regExp1 = new RegExp('\\<', 'g'),
        regExp2 = new RegExp('\\^', 'g'),
        regExp3 = new RegExp('\\(', 'g');
      console.log(regExp);
      let mobileU = decodeURIComponent(item.mu || '');
      mobileU = mobileU.replace(regExp, '?');
      mobileU = mobileU.replace(regExp1, '=');
      mobileU = mobileU.replace(regExp2, '&');
      mobileU = mobileU.replace(regExp3, '/');
      console.log('mobileU----', mobileU);
      item.url = mobileU;
      // `https://cs.yjt361.com${mobileU}`;
    } else {
      item.mu = '';
      item.url = '';
    }

    if (isPlayWithVideo(params)) {
      params.isShowVideo = '0';
      getVideoPlayBySP(params, `${useUrl}${item.url}`);
      return;
    }
    YouXin.openWindow({
      url: `${useUrl}${item.url}`, // 网页地址
      title: params.title,
      showHeader: header,
      screenMode: screenMode
    });
  }
}

// 增加资源类型
function setParamsType (param, bagItem) {
  const params = param;
  params.fileId = '';
  params.resId = params.id;
  params.type = 1;
  return params;
}

// 判断资源类型
function resOtherPlay (params, success) {
  const item = params,
    type = parseInt(item.resType) || parseInt(item.destType);
  if (type === 2 || type === 6) {
    // 试卷
    getPaperPlay(params);
    return true;
  }

  if (isApply(params)) {
    getApplyPlay(params);
    return true;
  }
  return false;
}

// 判断资源类型
function resOtherPlayByType (params, success) {
  const item = params,
    type = item.destType;
  if (parseInt(type) === 2) {
    // 试卷
    item.afterFormat = '4';
    item.transstate = '2';
    item.mobileChiefFlag = 1;
    const obj = {
      afterFormat: '4',
      list: [item],
      transstate: '2'
    };
    handlejudgePLay(obj, params, success);
    return true;
  } else if (type === '13' || type === 13 || type === 5) {
    // 应用
    if (item.mu !== 'undefined' && item.mu !== '') {
      const regExp = new RegExp('\\>', 'g'),
        regExp1 = new RegExp('\\<', 'g'),
        regExp2 = new RegExp('\\^', 'g'),
        regExp3 = new RegExp('\\(', 'g');
      console.log(regExp);
      let mobileU = decodeURIComponent(item.mu || '');
      mobileU = mobileU.replace(regExp, '?');
      mobileU = mobileU.replace(regExp1, '=');
      mobileU = mobileU.replace(regExp2, '&');
      mobileU = mobileU.replace(regExp3, '/');
      // console.log('mobileU----', mobileU);
      item.url = mobileU;
      // `https://cs.yjt361.com${mobileU}`;
    } else {
      item.mu = '';
      item.url = '';
    }

    item.afterFormat = '4';
    item.transstate = '2';
    const obj = {
      afterFormat: '4',
      list: [item],
      transstate: '2',
      linkType: 1
    };
    handlejudgePLay(obj, params, success);
    return true;
  }
  return false;
}

/**
 * 判断类型
 * @param {} row
 */
function getFileType (row) {
  const ary = row.list || [];
  if (!ary || ary.length === 0) {
    return 'none';
  }
  if (row && row.linkType === 1) {
    return 'word';
  }
  const mainFile = ary.find((item) => item.mobileChiefFlag === 1)
    ? ary.find((item) => item.mobileChiefFlag === 1)
    : ary[0]; // 主文件
  let type = 'word';
  switch (Number(mainFile.afterFormat)) {
    case 1:
      type = 'video';
      break;
    case 2:
      type = 'audio';
      break;
    case 3:
      type = 'img';
      break;
    case 4:
      type = 'word';
      break;
    case 5:
      type = 'none';
      break;
    default:
      break;
  }
  return type;
}

/**
 * 播放接口调用
 */
async function getPlayList (params) {
  const local = localStorage.getItem('loginDataMobile') ? JSON.parse(localStorage.getItem('loginDataMobile')) : {};
  let docPreviewType = '0';
  if (local.docPreviewType) {
    docPreviewType = local.docPreviewType;
  }
  const info = {
      ct: '0',
      fileType: '0',
      resId: params.resId,
      fileId: params.fileId,
      docPreviewType: docPreviewType
    },
    res = await playServices.getPlayList(info);
  if (res.data.list.length > 0) {
    const backData = res.data.list[0];
    return backData;
  } else {
    return [];
  }
}

// 判断是不是 应用类型
export function isApply (params) {
  const type = params.destType || params.type;
  if (type === 13 || type === '13' || type === 5) {
    return true;
  } else {
    return false;
  }
}
// 判断 需不需要展示安全区域
export function isSafeArea (param) {
  if (param.safeArea && param.safeArea === '1') {
    return true;
  } else {
    return false;
  }
}

// 判断是不是 需要返回按钮
export function isApplyBack (param) {
  if (param.returnBtn && param.returnBtn === '1') {
    return true;
  } else {
    return false;
  }
}

// 判断是不是 需要嵌套
export function isNeedNest (param) {
  if (param.nest && param.nest === '1') {
    return true;
  } else {
    return false;
  }
}

// 判断是不是 横屏
export function isLandscape (param) {
  if (param.landscape && param.landscape === '1') {
    return true;
  } else {
    return false;
  }
}

// 判断是不是 需要视频窗口播放
export function isPlayWithVideo (param) {
  if (param.openWithVideo && param.openWithVideo === '1') {
    return true;
  } else {
    return false;
  }
}

/**
 * 是不是全屏播放
 * @param {*} source
 */
function isFullScreen (source) {
  return true;
}

/**
 * 是不是小框口播放
 * @param {*} type
 */
function isAVScreen (type) {
  if (type === 'video' || type === 'audio') {
    return true;
  } else {
    return false;
  }
}

/**
 * 组装分享 参数 目前分享的为课程分享参数
 * @param {*} param
 */
export function assembleSharePara (param) {
  YouXin.getLoginInfo({
    success (loginInfo) {
      console.log('loginInfo', loginInfo);
    }
  });
  // param.platform = '1,2,3,4,5';
  // param.type = '4';
  // param.title = '';
  // param.iconUrl = `${window.hostOrigin}nrmsui/public_static/pc/resdef_poster/defPersonal.png`;
  // param.pageUrl = `${window.hostOrigin}play/share/play?rcode=${param.id}&source=student&resType=filed&sharePath=play&refer=${window.hostOrigin}`;
  // param.desc = '全科同步学，成绩更优异';
  return param;
}

/**
 *
 * @param {*} v  资源数据
 * @param {*} source 入口场景
 * @param {*} params 相关参数
 * @param {*} success 音视频播放成功回调
 */
function handlejudgeLogic (v, params, resolve) {
  const type = getFileType(v),
    source = params.source;
  if (isFullScreen(source)) {
    if (isAVScreen(type)) {
      YouXin.onVideoPlayEnd({
        // 请求成功的 回调
        success: (totalTime, playTime, currentTime) => {
          const obj = {
            totalTime: parseInt(totalTime),
            playTime: parseInt(playTime),
            currentTime: parseInt(currentTime)
          };
          console.log('视频播放的进度-----', obj);
          if (obj.totalTime === 0) {
            resolve(0);
          } else {
            if (obj.currentTime < obj.totalTime) {
              const finish = 50;
              resolve({ finish, obj });
            } else if (obj.currentTime >= obj.totalTime) {
              const finish = 100;
              resolve({ finish, obj });
            }
          }
        }
      });
      // 音频 播放进度
      playVideoOrAudio(v, params, resolve);
    } else {
      const finish = 100;
      resolve({ finish });
      getOtherPlay(params);
    }
  } else {
    if (isAVScreen(type)) {
      getVideoPlay(params);
    } else {
      getOtherPlay(params);
    }
  }
}
/**
 * 处理播放逻辑
 * @param {} v
 * @param {*} params
 * @param {*} success
 */
function handlejudgePLay (row, params, success) {
  const ary = row.list || [],
    mainFile = ary.find((item) => item.mobileChiefFlag === 1) ? ary.find((item) => item.mobileChiefFlag === 1) : ary[0], // 寻找主文件
    config = {},
    shareConfig = {};
  let type = '';
  mainFile.resDescribe = row.resDescribe || ''; // 添加描述字段
  if (!mainFile.url) {
    const transstate = mainFile.transstate,
      configError = handlePlayError(row, params, transstate);
    success(configError);
    return false;
  }

  if (row.linkType && row.linkType === 1) {
    mainFile.afterFormat = '4';
  }

  switch (Number(mainFile.afterFormat)) {
    case 1:
      config.currentUrl = jointPlayDomain(mainFile.url, mainFile.playUrlFlag);
      type = 'video';
      break;
    case 2: {
      const audio = ary.filter((item) => Number(item.afterFormat) === 2);
      mainFile.id = mainFile.id || mainFile.fileId || mainFile.resId || '';
      config.audios = audio.map((item) => {
        return {
          title: item.showFileName || item.fileName || '',
          url: jointPlayDomain(item.url || '', item.playUrlFlag),
          id: item.id || item.fileId || item.resId || ''
        };
      });
      config.currentUrl = jointPlayDomain(mainFile.url, mainFile.playUrlFlag);
      config.currentId = mainFile.id;
      type = 'audio';
      break;
    }
    case 3: {
      const imgs = ary.filter((item) => Number(item.afterFormat) === 3);
      config.imageList = imgs.map((item) => {
        return { showFileName: item.showFileName || '', url: jointPlayDomain(item.url || '', item.playUrlFlag) };
      });
      config.currentUrl = jointPlayDomain(mainFile.url, mainFile.playUrlFlag);
      type = 'img';
      break;
    }
    case 4:
      if (isApply(params)) {
        config.currentUrl = mainFile.url;
      } else {
        config.currentUrl = jointPlayDomain(mainFile.url, mainFile.playUrlFlag);
      }
      type = 'word';
      break;
    case 6:
      config.currentUrl = jointPlayDomain(mainFile.url, mainFile.playUrlFlag);
      type = 'pdf';
      break;
    case 5:
      type = 'none';
      config.currentUrl = '';
      break;
  }
  console.log('config----', config);
  config.currentItem = mainFile;
  config.fileType = type;
  shareConfig.title = row.title;
  shareConfig.desc = row.resDescribe;
  shareConfig.iconUrl = mainFile.formatIconUrl;
  if (config.currentUrl === '') {
    // 播放失败
    params.fileType = type;
    const configError = handlePlayError(row, params, mainFile.transstate);
    success(configError, shareConfig);
  } else {
    config.currentItem.title = params.title;
    PVCollector.getNormalStaticParam(PVCollector.STU_EVENT_ID.RMS_COURSE_PLAY, { resInfo: mainFile });
    success(config, shareConfig);
  }
}

function handlePlayError (v, params, transstate) {
  let errorText = '';
  if (v && v.linkType && v.linkType === 1) {
    errorText = '很抱歉资源打开失败！';
  } else {
    errorText = '该资源暂不支持手机端播放！';
  }

  switch (transstate) {
    case '0':
      errorText = '很抱歉资源未转码！';
      break;
    case '1':
      errorText = '很抱歉资源正在转码中！';
      break;
    case '3':
      errorText = '很抱歉资源转码失败！';
      break;
    case '4':
      errorText = '很抱歉资源无法转码！';
      break;
    default:
      break;
  }
  if (params.fileType && params.fileType === 'none') {
    errorText = '该资源不支持线上播放，请到PC端下载使用';
  }
  const config = {
    errorText: errorText,
    title: params.title,
    currentUrl: ''
  };
  return config;
}

/**
 * 根据域名获取 拼接对应的播放地址
 */
export function jointPlayDomain (url, playUrlFlag) {
  const local = localStorage.getItem('loginDataMobile') ? JSON.parse(localStorage.getItem('loginDataMobile')) : {};
  let dUrl = url;
  switch (playUrlFlag) {
    case 0:
      break;
    case 1:
      dUrl = `${local.play_sysvodd_url}${url}`;
      break;
    case 2:
      dUrl = `${local.NATIONAL_PORTAL_Domain}${url}`;
      break;
    case 3:
      dUrl = `${local.play_localvodd_url}${url}`;
      break;
    case 4:
      dUrl = `${window.location.origin}${url}`;
      break;
    default:
      break;
  }
  console.log('local', local, 'dUrl-----', dUrl);
  return dUrl;
}

/**
 *组装播放参数
 * @param {*} params
 * @param {*} bagItem
 * @param {*} success
 * @returns
 */
export function assemblePlayParams (item, source) {
  return {
    id: item.destCode,
    catId: item.sourceCode,
    paramTags: '',
    source: source,
    extension: item.extension || '',
    spendTime: item.spendTime || 0,
    title: item.destTitle || item.name || '',
    destType: item.destType || '',
    returnBtn: item.returnBtn ? item.returnBtn : undefined,
    landscape: item.landscape ? item.landscape : undefined,
    nest: item.nest ? item.nest : undefined,
    safeArea: item.safeArea,
    mu: getMobileUrl(item),
    ...item.properties,
    pageItem:
      item.sourceFormat === 'F300' && item.paperList && item.paperList.length > 0 ? item.paperList[0] : undefined
  };
}
/**
 * 点击资源时 入口判断
 * @param {*} params
 * @param {*} bagItem
 * @param {*} success
 */
export async function judgePlay (params, bagItem, success) {
  return new Promise(function (resolve, reject) {
    const para = setParamsType(params),
      other = resOtherPlay(params, success);
    if (other !== true) {
      getPlayList(para).then((data) => {
        if (data.list && data.list.length > 0) {
          handlejudgeLogic(data, params, resolve);
        } else {
          success('');
        }
      });
    }
  });
}

export async function handlePlay (params, success) {
  const para = setParamsType(params),
    other = resOtherPlayByType(params, success);
  if (other !== true) {
    getPlayList(para).then((data) => {
      if (data.list && data.list.length > 0) {
        handlejudgePLay(data, params, success);
      } else {
        success('');
      }
    });
  }
}
